package com.ljw.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljw.hmall.clients.ItemClient;
import com.ljw.hmall.order.mapper.OrderDetailMapper;
import com.ljw.hmall.order.mapper.OrderMapper;
import com.ljw.hmall.order.pojo.Order;
import com.ljw.hmall.order.pojo.OrderDetail;
import com.ljw.hmall.pojo.NonWebRequestAttributes;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

@Component
@Slf4j
public class Consumer {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    ItemClient itemClient;


    @GlobalTransactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(value = "delay.direct", type = "direct"),
            key = "ttl"
    ))
    public void DelayQueue(String msg){
        String[] split = msg.split(",");
        String userId = split[0];
        String orderId = split[1];
        NonWebRequestAttributes request = new NonWebRequestAttributes();
        request.setAttribute("authorization",userId,0);
        RequestContextHolder.setRequestAttributes(request);

        log.info("开始消费消息...");
        System.out.println("接收到延迟消息：" + msg);
        Order order = orderMapper.selectById(orderId);
        Integer status = order.getStatus();
        if (status==1){
            //恢复库存
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,orderId);
            OrderDetail orderDetail1 = orderDetailMapper.selectOne(queryWrapper);
            Integer num = orderDetail1.getNum();
            Long itemId = orderDetail1.getItemId();
            itemClient.updateAddStock(itemId,num);
            //将status改为5
            order.setStatus(5);
            orderMapper.updateById(order);
            System.out.println("订单过期未支付，恢复库存");
        }else if (status==2){
            System.out.println("订单已经支付...丢弃消息");
            return;
        }
    }
}
